package com.sangmo.fts.basic.validation;

import com.sangmo.boot.framework.common.utils.ApplicationUtils;
import com.sangmo.boot.framework.plugin.dataview.validator.IExtraValidator;
import com.sangmo.boot.framework.plugin.dataview.validator.impl.ValidationContext;
import com.sangmo.boot.framework.plugin.dataview.validator.violation.DataViolation;
import com.sangmo.fts.basic.model.Company;
import com.sangmo.fts.basic.repo.CompanyRepo;
import org.apache.commons.beanutils.PropertyUtils;

import java.lang.reflect.Field;
import java.util.List;
import java.util.stream.Collectors;

public class StorageComValidator implements IExtraValidator {
    @Override
    public DataViolation validate(ValidationContext.DataFieldSource source, Object obj, Field field) {
        try {
            Object value = PropertyUtils.getProperty(obj, field.getName());

            CompanyRepo companyRepo = ApplicationUtils.getBean(CompanyRepo.class);
            List<Company> companyList = companyRepo.findByTypeAndDeleted(Company.Type.STORAGE, 0L);
            List<Long> companyIds = companyList.stream().map(Company::getId).collect(Collectors.toList());
            if (companyIds.contains((Long)value)) {
                return null;
            }
            return new DataViolation(source.root, obj, field.getName(), "error.datafield.company.notValid", value);
        }
        catch (RuntimeException ex) {
            throw ex;
        }
        catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
}
